#!/bin/bash

# 配置参数
OUTPUT_DIR="dist"
APP_NAME="DataMarker"
VERSION="1.0.2"
WINDOWS_ICON="static/images/favicon.ico"
MACOS_ICON="static/images/favicon.icns"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# 清理旧构建
echo -e "${GREEN}🧹 清理旧构建文件...${NC}"
rm -rf "$OUTPUT_DIR" 2>/dev/null
mkdir -p "$OUTPUT_DIR"

# 检查必要工具
check_dependency() {
  if ! command -v "$1" >/dev/null 2>&1; then
    echo -e "${RED}❌ 需要安装 $1 工具${NC}" >&2
    if [ -n "$2" ]; then
      echo -e "${YELLOW}安装命令: $2${NC}" >&2
    fi
    exit 1
  fi
}

check_dependency "zip"
check_dependency "rsrc" "go install github.com/akavel/rsrc@latest"

# 检查图标文件
[ ! -f "$WINDOWS_ICON" ] && echo -e "${YELLOW}⚠️ 警告: Windows图标文件 $WINDOWS_ICON 不存在${NC}"
[ ! -f "$MACOS_ICON" ] && echo -e "${YELLOW}⚠️ 警告: macOS图标文件 $MACOS_ICON 不存在${NC}"

# 统一编译函数
compile_target() {
  local os=$1
  local arch=$2
  local target_name=$3
  local output_suffix=$4
  local is_gui=$5
  
  echo -e "${GREEN}🔧 编译 $os ($target_name) 版本...${NC}"
  
local display_os="$os"
[[ "$os" == "darwin" ]] && display_os="macos"  # 仅影响文件名，不影响实际编译
local output_file="${APP_NAME}_v${VERSION}_${display_os}_${target_name}${output_suffix}"
  local build_cmd="CGO_ENABLED=0 GOOS=$os GOARCH=$arch go build -trimpath -ldflags=\"-s -w -X main.Version=$VERSION\" -tags \"moderncsqlite\" -o \"$OUTPUT_DIR/$output_file\" ."
  
  # Windows特殊处理
  if [ "$os" == "windows" ]; then
    if [ -f "$WINDOWS_ICON" ]; then
      echo -e "  ${GREEN}🖼️ 嵌入Windows图标..."
      cat > app.manifest <<EOF
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <assemblyIdentity version="1.0.0.0" processorArchitecture="*" name="${APP_NAME}" type="win32"/>
  <dependency>
    <dependentAssembly>
      <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*"/>
    </dependentAssembly>
  </dependency>
</assembly>
EOF
      rsrc -manifest app.manifest -ico "$WINDOWS_ICON" -o rsrc.syso
    fi
    
    # 根据是否为GUI程序调整构建参数
    if [ "$is_gui" == "gui" ]; then
      build_cmd="CGO_ENABLED=0 GOOS=$os GOARCH=$arch go build -trimpath -ldflags=\"-s -w -X main.Version=$VERSION -H=windowsgui\" -tags \"moderncsqlite\" -o \"$OUTPUT_DIR/$output_file\" ."
    fi
  fi
  
  # 执行编译
  eval $build_cmd
  
  # Windows清理
  if [ "$os" == "windows" ]; then
    [ -f "rsrc.syso" ] && rm rsrc.syso
    [ -f "app.manifest" ] && rm app.manifest
  fi
  
  # macOS特殊处理
  if [ "$os" == "darwin" ] && [ -f "$MACOS_ICON" ]; then
    echo -e "  ${GREEN}🖼️ 为macOS应用打包..."
    local temp_dir=$(mktemp -d)
    mkdir -p "$temp_dir/Contents/Resources" "$temp_dir/Contents/MacOS"
    
    cp "$MACOS_ICON" "$temp_dir/Contents/Resources/icon.icns"
    cp "$OUTPUT_DIR/$output_file" "$temp_dir/Contents/MacOS/${APP_NAME}"
    
    cat > "$temp_dir/Contents/Info.plist" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleExecutable</key>
    <string>${APP_NAME}</string>
    <key>CFBundleIconFile</key>
    <string>icon.icns</string>
    <key>CFBundleIdentifier</key>
    <string>com.yourcompany.${APP_NAME}</string>
    <key>CFBundleName</key>
    <string>${APP_NAME}</string>
    <key>CFBundleVersion</key>
    <string>${VERSION}</string>
    <key>CFBundleShortVersionString</key>
    <string>${VERSION}</string>
    <key>NSHighResolutionCapable</key>
    <true/>
    <key>LSMinimumSystemVersion</key>
    <string>10.13</string>
</dict>
</plist>
EOF
    
    mkdir -p "$OUTPUT_DIR/${output_file}.app/Contents"
    cp -R "$temp_dir/Contents" "$OUTPUT_DIR/${output_file}.app/"
    rm -rf "$temp_dir"
  fi
  
  # Linux特殊处理
  if [ "$os" == "linux" ]; then
    chmod +x "$OUTPUT_DIR/$output_file"
  fi
}

# 编译各平台目标
compile_target "windows" "amd64" "amd64" ".exe" "console"
compile_target "darwin" "amd64" "intel" "" ""
compile_target "darwin" "arm64" "arm64" "" ""
compile_target "linux" "amd64" "x86_64" "" ""
compile_target "linux" "arm64" "aarch64" "" ""

# 生成构建信息
echo -e "${GREEN}📝 生成版本信息...${NC}"
cat > "$OUTPUT_DIR/build-info.txt" <<EOF
应用名称: $APP_NAME
版本: $VERSION
构建时间: $(date +"%Y-%m-%d %H:%M:%S %Z")
Git Commit: $(git rev-parse --short HEAD 2>/dev/null || echo "未检出Git仓库")
Go版本: $(go version)
构建环境: $(uname -a)
EOF

# 打包和校验
echo -e "${GREEN}📦 压缩发布文件...${NC}"
cd "$OUTPUT_DIR" || exit 1
zip -r "${APP_NAME}_v${VERSION}_all_platforms.zip" \
  "${APP_NAME}_v${VERSION}_"* \
  build-info.txt

echo -e "${GREEN}🔐 生成校验和...${NC}"
find . -maxdepth 1 -type f -name "${APP_NAME}_v${VERSION}_*" ! -name "*.zip" ! -name "*.sha256" -exec shasum -a 256 {} \; > checksums.sha256
shasum -a 256 "${APP_NAME}_v${VERSION}_all_platforms.zip" >> checksums.sha256
cd ..

# 输出结果
echo ""
echo -e "${GREEN}✅ 构建成功！${NC}"
echo -e "📁 输出目录: $OUTPUT_DIR"
echo ""
echo -e "生成的文件:"
ls -lh "$OUTPUT_DIR/${APP_NAME}_v${VERSION}_"*
echo ""
echo -e "使用说明:"
echo -e "  ${YELLOW}Windows用户:${NC} 直接运行 ${APP_NAME}_v${VERSION}_windows_amd64.exe"
echo -e "  ${YELLOW}Mac用户:${NC}"
echo -e "    - 直接运行: chmod +x ${APP_NAME}_v${VERSION}_macos_* && ./${APP_NAME}_v${VERSION}_macos_*"
echo -e "    - 或使用应用包: open ${APP_NAME}_v${VERSION}_macos_*.app"
echo -e "  ${YELLOW}Linux用户:${NC}"
echo -e "    - 添加执行权限: chmod +x ${APP_NAME}_v${VERSION}_linux_*"
echo -e "    - 运行: ./${APP_NAME}_v${VERSION}_linux_*"